package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.Log;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;

//添加要购买的商品到购物车
public class AddItemToCartServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String SIGN_ON = "/WEB-INF/jsp/account/signonForm.jsp";
    //选择的所要添加到购物车的具体item的id
    private String workingItemId;
    private Cart cart = null;
    private CatalogService catalogService = new CatalogService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //账号为空时，让用户登录
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        if(account == null){
            String tip = "Please login at first.";
            session.setAttribute("tipInfo",tip);
            request.getRequestDispatcher(SIGN_ON).forward(request,response);
        }else {
            //获取要添加的item的信息
            workingItemId = request.getParameter("workingItemId");
            //加载数据库中的购物车
            cart = catalogService.getCartByUsername(account.getUsername());
            if (cart == null) {
                cart = new Cart();
            }
            //如果购物车内已经包含该item，则增加其数量
            if (cart.containsItemId(workingItemId)) {
                cart.incrementQuantityByItemId(workingItemId);
                catalogService.updateCartItem(account.getUsername(),workingItemId,cart.getQuantityByItemId(workingItemId));


            } else {
                boolean isInStock = catalogService.isItemInStock(workingItemId);
                Item item = catalogService.getItem(workingItemId);
                catalogService.insertCartItem(cart.addItem(item, isInStock),account.getUsername());
            }


            //时间
            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String datetime = tempDate.format(new java.util.Date());
            //信息
            String info = "将"+workingItemId+"加入购物车";
            Log log = new Log(account.getUsername(),datetime,info);
            //添加log
            new AccountService().addLog(log);


            session.setAttribute("cart", cart);
            request.getRequestDispatcher(VIEW_CART).forward(request, response);
        }
    }
}
